var globalOverlayManager;

function Money() {
	
}

function DayDetailPanel(config) {
	this.config = config;
	
	var el = config.el;
	
	YAHOO.util.Dom.removeClass(el, "display-hide");
	document.body.appendChild(YAHOO.util.Dom.get(el));
			
	this.panel = new YAHOO.widget.Panel(el, {
			width: "600px",
			modal: true,
			fixedcenter: true,
			constraintoviewport: true
	});
			
	this.panel.render();
	
	if (globalOverlayManager) {
		globalOverlayManager.register(this.panel);
	}
	
	var dataTable = this.dataTable = new DayDetailDataTable({
		el: this.config.dataTableEl
	});
	
	var tbArray = YAHOO.util.Dom.getElementsByClassName("tb", "div", this.panel.body);
	var len = tbArray.length;
	
	function addIncomeHandler() {
		money.showAccountDialog("in", dataTable);	
	}
	
	function addIncomeCallback() {
		
	}
	
	this.toolbar = new DayDetailToolbar(tbArray[0], {
		handlers: {
			addIncomeHandler: addIncomeHandler
		}
	});
}

DayDetailPanel.prototype = {
	show: function(date) {
		this.dataTable.load(date);
		this.panel.header.innerHTML = "Daily Detail - " + date;
		
		this.panel.show();
		
		if (globalOverlayManager) {
			globalOverlayManager.bringToTop(this.panel);
		}
	}
}

function DayDetailDataTable(config) {
	var divId = config.el;
	
	var columnDefs = [{
			key: "checked",
			label: "",
			formatter: YAHOO.widget.DataTable.formatCheckbox,
			width: "24px"
		}, {
			key: "date", 
			label: "Date", 
			formatter: YAHOO.widget.DataTable.formatDate,
			sortable: true
		}, {
			key: "category", 
			label: "Category", 
			sortable: true
		}, {
			key: "amount", 
			label: "Amount", 
			formatter: Money.formatAccountRecordAmount, 
			sortable: true
		}, {
			key: "description", 
			label: "Description", 
			sortable: true
		}
    ];

    dataSource = new YAHOO.util.DataSource("account.php?");
    dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    dataSource.connXhrMode = "queueRequests";
    
    dataSource.responseSchema = {
    	resultsList: "result",
        fields: [{
        	key: "id"
        }, {
        	key: "date"/*,
        	parser: YAHOO.util.DataSource.parseDate*/
        }, {
        	key: "category"
        }, {
        	key: "amount",
        	parser: YAHOO.util.DataSource.parseNumber
        }, {
        	key: "description"
        }, {
        	key: "type"
        }/*, {
        	key: "checked"
        }*/]
    };

    dataTable = new YAHOO.widget.DataTable(
    	divId, 
    	columnDefs, 
    	dataSource, 
    	{
    		initialRequest: "date"
    	}
    );
    
    
 	dataTable.subscribe("rowMouseoverEvent", dataTable.onEventHighlightRow);   
	dataTable.subscribe("rowMouseoutEvent", dataTable.onEventUnhighlightRow);
	
	var dddt = this; 
    dataTable.subscribe("rowClickEvent", function(oArgs) {
    	dddt.onEventSelectRow(oArgs)
    });
    
    YAHOO.util.Dom.addClass(dataTable.getTableEl(), "full-width");
    
    this.dataSource = dataSource;
    this.dataTable = dataTable;
	
}

DayDetailDataTable.prototype = {
	load: function(date) {
		this.dataSource.sendRequest("date=" + date, this.dataTable.onDataReturnInitializeTable, this.dataTable);
	},	
	onEventSelectRow: function(oArgs) {
		var evt = oArgs.event;
    	var target = oArgs.target;
    	
    	var record = this.dataTable.getRecord(target);
    	var id = record.getData("id");
    	
    	ShowAccountRecord(id);
	}
};

function DayDetailToolbar(el, config) {
	var Dom = YAHOO.util.Dom;
	var element = Dom.get(el);
	this.htmlElement = element;
	
	this.config = config;
	
	this.initButtons();
}

DayDetailToolbar.prototype = {
	initButtons: function() {
		var el = this.htmlElement.firstChild;
		
		do {
			var btnEl = el;
			el = el.nextSibling;
			
			if (1 == btnEl.nodeType) {
				if (btnEl.className == "add-btn") {
					var menu = this._getAddMenu();
					
					new YAHOO.widget.Button(btnEl, {
						type: "split",
						menu: menu,
						onclick: {
							fn: this.config.handlers.addIncomeHandler
						}
					});	
				} else {
					new YAHOO.widget.Button(btnEl, {
						type: "push"
					});
				}
			}
		} while (el)
	},
	_getAddMenu: function() {
		var sel = document.createElement("select");
		var opt = document.createElement("option");
		opt.innerHTML = "Income";
		sel.appendChild(opt);
		
		opt = document.createElement("option");
		opt.innerHTML = "Expense";
		sel.appendChild(opt);
		
		this.htmlElement.appendChild(sel);
		return sel;		
	}
}

function MonthStatisticDataTable(config) {
	var divId = config.statisticEl, 
		dataSourceId = config.dataSourceEl;
		 
	var columnDefs = [
        {key: "date", formatter: /*Money.formatDateButton*/YAHOO.widget.DataTable.formatDate, sortable: true, resizeable: true, label: "Date"},
		{key: "income", formatter: Money.formatGreenColorText, sortable: true, resizeable: true, label: "Income"},
        {key: "expend", formatter: Money.formatRedColorText, sortable: true, resizeable: true, label: "Expend"},
        {key: "total", formatter: Money.formatColorText, sortable: true, resizeable: true, label: "Total"}
	];
		
	var dataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get(dataSourceId));

	dataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
	dataSource.responseSchema = {   
		fields: [
			{key: "date"/*, parser: YAHOO.util.DataSource.parseDate*/},   
            {key: "income"},   
            {key: "expend", parser: YAHOO.util.DataSource.parseNumber},   
            {key: "total"} 
        ]   
	};

    var dataTable = new YAHOO.widget.DataTable(divId, columnDefs, dataSource, {
		//selectionMode: "single"
	});		
	
	YAHOO.util.Dom.addClass(dataTable.getTableEl(), "full-width");
	YAHOO.util.Dom.setStyle(dataSourceId, "display", "none");
	
	this.dataTable = dataTable;
	
	this.dataTable.subscribe("rowMouseoverEvent", this.dataTable.onEventHighlightRow);   
	this.dataTable.subscribe("rowMouseoutEvent", this.dataTable.onEventUnhighlightRow);   
	this.dataTable.subscribe("rowClickEvent", this.dataTable.onEventSelectRow); 

//	this.dataTable.subscribe("rowClickEvent", this.onEventSelectRow);

	var msdt = this;
	
	this.dataTable.subscribe("rowClickEvent", function(oArgs) {
		msdt.onEventSelectRow(oArgs);
	});
	
	this.config = config;
}

MonthStatisticDataTable.prototype = {
	onEventSelectRow: function(oArgs) {
		var evt = oArgs.event;
    	var target = oArgs.target;

		if (!this.detailPanel) {
			this.detailPanel = new DayDetailPanel({
				el: this.config.detailEl,
				dataTableEl: this.config.innerDataTableEl
			});
		}
		
		var date = YAHOO.util.Dom.getFirstChild(target).innerHTML;
		this.detailPanel.show(date);    	
	}
};


function MonthDetailPanel(id, config) {
	var panel = new YAHOO.widget.Panel(id, {
		width: "400px",
		constraintoviewport: true
	});
	
	panel.render();
	panel.show();
}

function MonthDetailDataTable(divId, dataSourceId, config) {
	var columnDefs = [
        {key: "date", formatter: /*Money.formatDateButton*/YAHOO.widget.DataTable.formatDate, sortable: true, resizeable: true, label: "Date"},
		{key: "category", /*formatter: Money.formatGreenColorText, */sortable: true, resizeable: true, label: "Category"},
        {key: "amount", formatter: Money.formatRedColorText, sortable: true, resizeable: true, label: "Amount"},
        {key: "description", /*formatter: Money.formatColorText, */sortable: true, resizeable: true, label: "Description"}
	];
		
	var dataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get(dataSourceId));

	dataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
	dataSource.responseSchema = {   
		fields: [
			{key: "date"},   
            {key: "category"},   
            {key: "amount", parser: YAHOO.util.DataSource.parseNumber},   
            {key: "description"}  
        ]   
	};

    var dataTable = new YAHOO.widget.DataTable(divId, columnDefs, dataSource, {
		//selectionMode: "single"
	});		
	
	YAHOO.util.Dom.addClass(dataTable.getTableEl(), "full-width");
	YAHOO.util.Dom.setStyle(dataSourceId, "display", "none"); 
}

Money.formatAccountRecordAmount = function(el, record, column, data) {
	el.innerHTML = "";
	
	var type = record.getData("type");
	var color = type == "in" ? "green" : "red";
	
	el.innerHTML = ["<font color='", color, "'>", data, "</font>"].join("");
}

Money.getSelect = function() {
	var sel = document.createElement("select");
	var len = arguments.length;
	for (var idx = 0; idx < len; idx++) {
		var opt = document.createElement("option");
		opt.innerHTML = arguments[idx];
		
		sel.appendChild(opt);
	}
	
	return sel;
}

Money.formatDateButton = function(el, record, column, data) {
	el.innerHTML = "";
	
	var btn = document.createElement("button");
	el.appendChild(btn);
	
	var menu = Money.getSelect("Add Income", "Add Expenditure", "Overview");
	el.appendChild(menu);
	
	new YAHOO.widget.Button(btn, {
		label: data,
		type: "split",
		menu: menu
	});
}

Money.formatEditButton = function(el, record, column, data) {
	/* Maybe effecient problem */
	el.innerHTML = "";
		
	var btn = document.createElement("button");
	
	el.appendChild(btn);
	
	new YAHOO.widget.Button(btn, {
		label: "Edit",
		className: "icon-only-button edit-icon",
		onclick: {
			fn: function() { AccountHelper.showAccountRecord(data) }
		}
	});
};

Money.formatDeleteButton = function(el, record, column, data) {
	/* Maybe effecient problem */
	el.innerHTML = "";
		
	var btn = document.createElement("button");
	
	el.appendChild(btn);
	
	new YAHOO.widget.Button(btn, {
		label: "Delete",
		className: "icon-only-button remove-icon",
		onclick: {
			fn: function() { AccountHelper.removeAccountRecord(data) }
			//obj: data,
			//scope: this
		}
	});
};

Money.formatColorText = function(el, record, column, data) {
	var val = parseInt(data);
	var col = "green";
	
	if (val < 0) {
		col = "red";
	}
	el.innerHTML = ["<font color='", col, "'>", data, "</font>"].join("");
};

Money.parseBoolean = function(data) {
	return false;
}

Money.formatRedColorText = function(el, record, column, data) {
	el.innerHTML = "<font color='red'>" + data + "</font>"
};

Money.formatGreenColorText = function(el, record, column, data) {
	el.innerHTML = "<font color='green'>" + data + "</font>"
};

Money.prototype = {
	initSystem: function() {
		YAHOO.util.Dom.addClass(document.body, "yui-skin-sam");
		
		this.addInButton = new YAHOO.widget.Button("add-in", {
			id: "add-in-button",
			className: "icon-button add-icon",
			onclick: {
				fn: function() { this.showAccountDialog("in"); },
				obj: null,
				scope: this
			}
		});
		this.addOutButton = new YAHOO.widget.Button("add-out", {
			id: "add-out-button",
			className: "icon-button add-icon",
			onclick: {
				fn: function() { this.showAccountDialog("out"); },
				obj: null,
				scope: this
			}
		});
		
		/*
		this.viewInButton = new YAHOO.widget.Button("view-in", {
			id: "view-in-button",
			className: "icon-button view-icon",
			onclick: {
				fn: function() { this.activeTab("in"); },
				obj: null,
				scope: this
			}
		});
		this.viewOutButton = new YAHOO.widget.Button("view-out", {
			id: "view-out-button",
			className: "icon-button view-icon",
			onclick: {
				fn: function() { this.activeTab("out"); },
				obj: null,
				scope: this
			}
		});
		*/
		
		this.bodyTabPanel = new YAHOO.widget.TabView("account-info-tab-view", {
			id: "account-info-tab-view",
			activeIndex: 1,
			orientation: "top"
		});
		
		this.accountRecordTabPanel = new YAHOO.widget.TabView("statistic-tab-view", {
			id: "account-daily-info-tab-view",
			activeIndex: 1,
			orientation: "left"
		});
		
		this.boardPanel = new YAHOO.widget.Panel("board", {
			id: "board-panel",
			x: 100,
			//fixedcenter: true,
			close: false,
			underlay: "shadow",
			width: "800px",
			visible: true,
			draggable: false
		});
		
		this.boardPanel.render();
		this.boardPanel.show();
		
		this.overlayManager = this.initOverlayManager();
		this.overlayManager.register(this.boardPanel);
		
		this.initComponent();
		this.initConnectEventTip();
	},
	initConnectEventTip: function() {
		var Dom = YAHOO.util.Dom,
			Connect = YAHOO.util.Connect;
		
		function showTip() {
			Dom.setStyle("loading-tip", "display", "inline");
		};
		
		function hideTip() {
			Dom.setStyle("loading-tip", "display", "none");
		};
		
		Connect.startEvent.subscribe(showTip);
		Connect.completeEvent.subscribe(hideTip);
	},
	initOverlayManager: function() {
		var mgr = globalOverlayManager = new YAHOO.widget.OverlayManager();
		return mgr;
	},
	initComponent: function() {
		var mgr = this.overlayManager
		this.inAccountDialog = this.initAccountDialog({
			templateId: "account-in-dialog-template",
			dialogId: "account-in-dialog",
			addCategoryButtonId: "add-in-catalog-button",
			addCategoryCallback: function() { ShowInAddCategoryPanel(mgr); },
			calendarButtonEl: "add-in-calendar-button",
			calendarEl: "add-in-canlendar",
			dateInputEl: "add-in-date-input"
		});
		
		this.outAccountDialog = this.initAccountDialog({
			templateId: "account-out-dialog-template",
			dialogId: "account-out-dialog",
			addCategoryButtonId: "add-out-catalog-button",
			addCategoryCallback: function() { ShowOutAddCategoryPanel(mgr); },
			calendarButtonEl: "add-out-calendar-button",
			calendarEl: "add-out-canlendar",
			dateInputEl: "add-out-date-input"
		});
		
		this.overlayManager.register([this.inAccountDialog, this.outAccountDialog]);
		
		this.initDataTable();
		
		var len = monthStatisticTable.length;
		for (var idx = 0; idx < len; idx++) {
			var month = monthStatisticTable[idx];
			new MonthStatisticDataTable({
				statisticEl: "div-statistic-" + month,
				dataSourceEl: "table-" + month,
				detailEl: "div-detail-" + month,
				innerDataTableEl: "div-detail-data-table-" + month
			}); 
//			new MonthDetailPanel("div-detail-" + month);
			
//			new MonthDetailDataTable("div-in-" + month, "table-in-" + month); 
//			new MonthDetailDataTable("div-out-" + month, "table-out-" + month); 
		} 
		
//		new MonthDetailDataTable("div-in-2007-12", "table-in-2007-12"); 
//		new MonthDetailDataTable("div-out-2007-12", "table-out-2007-12"); 
	},
	initAccountDialog: function(config) {
		var accountDialog = new YAHOO.widget.Dialog(config.templateId, {
			id: config.dialogId,
			width: "320px",
			modal: false,
			constraintoviewport: true,
			fixedcenter: true,
			visible: false,
			postmethod: "async",
			buttons : [{
				text:"Submit",
				isDefault: true,
				handler: function() {
					return function() {
						this.submit();
					}
				}()
			}, {
				text:"Cancel",
				handler: function() {
					return function() {
						this.hide();
					}
				}()
			}]
		});
		
		accountDialog.callback.failure = function() {
			alert("FAL");
		};
		accountDialog.callback.success = function() {
			var m = this;
			return function(req) {
				m.handleAddSuccess(req);
			}
		}.call(this);
		
		var addCatalogButton = new YAHOO.widget.Button(config.addCategoryButtonId, {
			label: "Add",
			className: "icon-only-button add-icon",
			onclick: {
				fn: config.addCategoryCallback
			}
		});
		
		var calendarContainer = new YAHOO.widget.Overlay(config.calendarEl);
		var result = calendarContainer.render();

		calendarContainer.align();
		
		calendarContainer.body.id = config.calendarEl + "_c";
		
		YAHOO.util.Dom.setStyle(calendarContainer.body, "border", "1px solid #808080");
		
		var calendar = new YAHOO.widget.Calendar(calendarContainer.body.id, {
			mindate: "1/1/2006",   
			maxdate: "12/31/2008"			
		});
		
		function onEventSelect(type, args, obj) {
			var dates = args[0];   
			var date = dates[0];   
			var year = date[0], month = date[1], day = date[2];   

			var dateInput = document.getElementById(config.dateInputEl);   
			dateInput.value = [year, "-", month, "-", day].join("");
			
			calendar.hide();			
		}
		
		calendar.selectEvent.subscribe(onEventSelect, calendar, true);
		
		var calendarButton = new YAHOO.widget.Button(
			config.calendarButtonEl, {
			label: "Choose",
			className: "icon-only-button view-icon",
			onclick: {
				fn: function() {
					calendar.show();
				}
			}
		});
		
		calendar.render();
		calendar.hide();
		
		accountDialog.render();
		
		return accountDialog;
	},
	initDataTable: function() {		
		var statsColumnDefs = [
			{key: "category", sortable: true, resizeable: true, width: "80px", label: "Category"},
			{key: "count", formatter: YAHOO.widget.DataTable.formatNumber, sortable: true, resizeable: true, label: "Count"},
            {key: "amount", formatter: Money.formatColorText, sortable: true, resizeable: true, label: "Total Amount"}
		];
		
		var statsDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("stats-table"));

		statsDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
		statsDataSource.responseSchema = {   
			fields: [{key: "category"},   
                    {key:"count", parser: YAHOO.util.DataSource.parseNumber},   
                    {key:"amount", parser: YAHOO.util.DataSource.parseNumber}    
            ]   
		};
		
		this.statsDataTable = new YAHOO.widget.DataTable("stats-data-table", statsColumnDefs, statsDataSource, {/*caption:"Money Income"*/});
		YAHOO.util.Dom.addClass(this.statsDataTable.getTableEl(), "full-width");		
	},
	showAccountDialog: function(type, dataTable) {
		alert(dataTable);
		if (type == "in") {
			this.inAccountDialog.show();
			this.overlayManager.bringToTop(this.inAccountDialog);	
		} else {
			this.outAccountDialog.show();
			this.overlayManager.bringToTop(this.outAccountDialog);
		}
	},
	hideAccountDialog: function(type) {
		if (type == "in") {
			this.inAccountDialog.hide();	
		} else {
			this.outAccountDialog.hide();
		}
	},
	handleAddSuccess: function(req) {
		var record = YAHOO.lang.JSON.parse(req.responseText);
		var id = record.id;
		record.edtoper = id;
		record.deloper = id;
		
		if (record.type == "in") {
			this.inDataTable.addRow(record);	
		} else {
			this.outDataTable.addRow(record);
		}
		
	}
	
};

var money = new Money();

YAHOO.util.Event.addListener(window, "load", function() { money.initSystem(); });